import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/store'
import _this from '../main.js'
import menu from './menu'
import axios from '@/utils/axios'
const originalPush = Router.prototype.push
const originalReplace = Router.prototype.replace
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
Router.prototype.replace = function push(location) {
  return originalReplace.call(this, location).catch(err => err)
}
Vue.use(Router)

let isAddRoutes = false // 是否已添加路由

const router = new Router({
  mode: 'history',
  base: '/',
  routes: []
})

// function getDropdownList (directory) {
//   return new Promise(async (resolve, reject) => {
//     try {
//       const { ResultSet } = await axios.post(domainData, { loadOnStartup: true, organizationId:1 })
//       resolve(ResultSet)
//     } catch (err) {
//       console.log(err)
//       reject(err)
//     }
//   })
// }

router.beforeEach(async (to, from, next) => {
  if (!isAddRoutes) {
    // 生成动态路由
    const list = []
    list.push({
      path: '*',
      redirect: { name: 'index' }
    })
    menu.forEach(item => {
      list.push({ ...item, path: `${item.path}` })
    })
    router.addRoutes(list)
    isAddRoutes = true
    next({ ...to, replace: true })
    // getDropdownList().then((ResultSet) => {
    //   store.dispatch('changeDropdown', ResultSet.Result)
    // })
  } else {
    if (!store.getters.name && to.name !== 'login') store.dispatch('loadUserInfo', { next, to })
    else next()
    // next()
  }
})
router.afterEach((to, from, next) => {
  document.getElementsByClassName('view')[0].scrollTo(0, 0)
})
export default router
